package com.jeesit.cloud.spot.web.api_controller.title_linkman;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeesit.cloud.annotation.ModuleLog;
import com.jeesit.cloud.constants.LogConstant;
import com.jeesit.cloud.dto.JSONResult;
import com.jeesit.cloud.dto.LogInfo;
import com.jeesit.cloud.dto.TitleLinkmanDto;
import com.jeesit.cloud.model.TitleLinkman;
import com.jeesit.cloud.model.User;
import com.jeesit.cloud.spot.service.ITitleLinkmanService;
import com.jeesit.cloud.util.ExportExcel;
import com.jeesit.cloud.validate.CreateAction;
import com.jeesit.cloud.validate.QueryAction;
import com.jeesit.cloud.validate.UpdateAction;
import com.jeesit.cloud.verify.UserAuthDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *   相关接口
 *　　
 *   @description TitleLinkman 接口
 *   ---------------------------------
 *   @author 漆传涛
 *   @date 2024-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/auth/v1/title_linkman")
@Api(tags = {"客商联系人"})
public class TitleLinkmanController {

    @Autowired
    private ITitleLinkmanService titleLinkmanService;

    /**
     * @description 获取分页列表
     * ---------------------------------
     * @author 漆传涛
     * @date 2024-01-09
     */
    @ApiOperation("获取分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "pageNo", value = "页码", dataTypeClass = Integer.class , paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页行数，最少10条，最多100条", dataTypeClass = Integer.class , paramType = "query", required = true)
    })
    //@PreAuthorize("hasAnyAuthority('SUPER_ADMIN','BACKGROUND_USER','COMPANY_USER','INDIVIDUAL_USER','SSE_USER')")
    @PostMapping(value = "/title_linkman_page")
    public JSONResult<Page<TitleLinkman>> getTitleLinkmanPage(Authentication authentication,@Validated(QueryAction.class)TitleLinkmanDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        Page<TitleLinkman> page=new Page<TitleLinkman>(dto.getPageNo(), dto.getPageSize());
        titleLinkmanService.page(page,dto);
        JSONResult<Page<TitleLinkman>> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setData(page);
        return res;
    }

/**
     * @description 获取列表
     * ---------------------------------
     * @author 漆传涛
     * @date 2024-01-09
     */
    @ApiOperation("获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "size", value = "查询数量，最多查询1000条", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    //@PreAuthorize("hasAnyAuthority('SUPER_ADMIN','BACKGROUND_USER','COMPANY_USER','INDIVIDUAL_USER','SSE_USER')")
    @PostMapping(value = "/title_linkman_list")
    public JSONResult<TitleLinkman> getTitleLinkmanList(Authentication authentication, @Validated(QueryAction.class)TitleLinkmanDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<TitleLinkman> list = titleLinkmanService.list(dto.getSize(),dto);
        JSONResult<TitleLinkman> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setDatas(list);
        return res;
    }


    /**
     * @description 导出列表
     * ---------------------------------
     * @author 漆传涛
     * @date 2024-01-09
     */
    @ApiOperation("导出列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('TitleLinkman_Export','SUPER_ADMIN')")
    @PostMapping(value = "/title_linkman_export")
    public void export(HttpServletResponse response,Authentication authentication, @Validated(QueryAction.class)TitleLinkmanDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<TitleLinkman> datas = titleLinkmanService.list(0,dto);
        String[] header = new String[]{"","姓名","类型 0业务联系人 1点价联系人","职务","负责业务","办公电话","移动电话","qq","微信","邮箱","传真","备注","签约抬头id","创建时间","创建人","创建人id","修改时间","修改人","修改人id","",""};
        List<List<Object>> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.00");
        for(TitleLinkman it : datas){
            List<Object> data = new ArrayList<>();
            data.add(it.getUuid());
            data.add(it.getLinkman());
            data.add(it.getLinkmanType());
            data.add(it.getJob());
            data.add(it.getBusiness());
            data.add(it.getOfficePhone());
            data.add(it.getMobileTelephone());
            data.add(it.getQq());
            data.add(it.getWechat());
            data.add(it.getMailbox());
            data.add(it.getFax());
            data.add(it.getRemark());
            data.add(it.getTitleUuid());
            data.add(Optional.ofNullable(it.getAddTime()).map(s->sdf.format(s)).orElse(""));
            data.add(it.getAddUserName());
            data.add(it.getAddUserUuid());
            data.add(Optional.ofNullable(it.getModTime()).map(s->df.format(s)).orElse(""));
            data.add(it.getModUserName());
            data.add(it.getModUserUuid());
            data.add(it.getDeleted());
            list.add(data);
        }
        ExportExcel excel = new ExportExcel();
        excel.setName("");
        excel.exportToExcel(response,header,list,0);
    }

    /**
     * @description 新建
     *
     * @author 漆传涛
     * @date 2024-01-09
     */
    @ApiOperation("新建")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('TitleLinkman_Add','SUPER_ADMIN')")
    @ModuleLog("TitleLinkman")
    @PostMapping("/title_linkman_add")
    public JSONResult<TitleLinkman> saveNewEntity(HttpServletRequest request,Authentication authentication, @Validated(CreateAction.class) TitleLinkmanDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<TitleLinkman> res= saveData(user,null,entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "保存，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    /**
     * @description 更新
     *
     * @author 漆传涛
     * @date 2024-01-09
     */
    @ApiOperation("更新 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('TitleLinkman_Modify','SUPER_ADMIN')")
    @ModuleLog("TitleLinkman")
    @PostMapping("/title_linkman_edit")
    public JSONResult<TitleLinkman> saveEditEntity(HttpServletRequest request,Authentication authentication,@Validated(UpdateAction.class) TitleLinkmanDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<TitleLinkman> res= saveData(user,entity.getUuid(),entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "更新，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    private JSONResult<TitleLinkman> saveData(User user,Long id,TitleLinkmanDto entity){
        JSONResult<TitleLinkman> res = new JSONResult<>();
        TitleLinkman it = new TitleLinkman();
        if(id==null){
            it.setDeleted(false);
        } else {
            it = titleLinkmanService.getById(entity.getUuid());
        }
        it.setUuid(entity.getUuid());
        it.setLinkman(entity.getLinkman());
        it.setLinkmanType(entity.getLinkmanType());
        it.setJob(entity.getJob());
        it.setBusiness(entity.getBusiness());
        it.setOfficePhone(entity.getOfficePhone());
        it.setMobileTelephone(entity.getMobileTelephone());
        it.setQq(entity.getQq());
        it.setWechat(entity.getWechat());
        it.setMailbox(entity.getMailbox());
        it.setFax(entity.getFax());
        it.setRemark(entity.getRemark());
        it.setTitleUuid(entity.getTitleUuid());
        it.setAddTime(entity.getAddTime());
        it.setAddUserName(entity.getAddUserName());
        it.setAddUserUuid(entity.getAddUserUuid());
        it.setModTime(entity.getModTime());
        it.setModUserName(entity.getModUserName());
        it.setModUserUuid(entity.getModUserUuid());
        it.setDeleted(entity.getDeleted());
        titleLinkmanService.saveOrUpdate(it);
        res.setData(it);
        res.setSuccess(true);
        res.setMessage("保存成功");
        return res;
    }


    /**
     * @description 删除
     *
     * @author 漆传涛
     * @date 2024-01-09
     */
    @ApiOperation("删除")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
        @ApiImplicitParam(name = "ids", value = "删除id（支持批量删除）", dataTypeClass = Long.class , allowMultiple = true,paramType = "query", required = true),
    })
    @PreAuthorize("hasAnyAuthority('TitleLinkman_Remove','SUPER_ADMIN')")
    @ModuleLog("TitleLinkman")
    @PostMapping("title_linkman_del")
        public JSONResult<Void> delEntity(HttpServletRequest request,Authentication authentication,@Size(min=1,max=50,message = "请选择要删除数据") Long[] ids) throws Exception{
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<Void> res = new JSONResult<>();
        for(int i=0;i<ids.length;i++){
            TitleLinkman it = titleLinkmanService.getById(ids[i]);
            titleLinkmanService.removeById(it.getUuid());
        }
        request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "删除，数据ID:" + StringUtils.join(ids)));
        res.setMessage("删除成功");
        res.setSuccess(true);
        return res;
    }

}

